import QtQuick 2.5
import "../Widgets"
import "./../../painter.js" as Painter
import QtQuick.Dialogs 1.2
import QtQuick.Controls 1.4
import SerialPortManager 1.0
Item {
    id:root
    //background
    property int currentGroup:1
    property int currentStove:5
    property int currentPainState:0//0为线性图，1为直方图
    property int currentPortIndex:0//串口索引值
    property bool readyReciveData:false//串口接收状态
    //属性变化时会发送属性名拼接Changed的信号例子信号CurrentGroupChanged
    //处理onCurrentGroupChanged

//    /*炉管颜色设置*/
    property var tube_in_content_color:"#45cc45";
    property var tube_out_content_color:"#cc9010";
    property var tube_cot_content_color:"#12cccc";


    //排错检测
    function checkStr(str){
        //排错1
        //校检符号为,的个数，是否整齐，单段104个
        //match根据正则检索字符串，正则带g则检测所有并返回数组
        var seg1=String(str).match(new RegExp(",","g"));
        console.log("number is,",seg1.length);

        //校检符号位#的个数是否整齐，单端8个
        var seg2=String(str).match(new RegExp("#","g"));
        console.log("number is,",seg2.length);
        //如果str为<呢？在下方可检测
        if((seg1.length%104!==0||seg2.length%8!==0)&&seg2.length>0&&seg1.length>0){
            return false;
        }

        //排错2
        var value=str.toString().split("??");


        /*删除换行符的数据，占两个字符*/
        for(var a=0;a<value.length;a++){
            if(value[a].length===2){
                value.splice(a,1);//删除位置与删除数量
            }
        }

        if(value.length%9===0&&value.length>0){
            return true;
        }
        else{
            return false;
        }
    }

    //刷新第n组的入管，出管，cot数据
    function refreshNewestDatas(){
        var tubeInTempData=server.access_tube_in_temp();
        //返回JSON数组存储带有temp温度time时间属性的JSON对象四千多条
        var tubeOutTempData=server.access_tube_out_temp();
        //同上出入管的区别而已

        var ctx=canvas.getContext('2d');
        ctx.clearRect(0,0,canvas.width,canvas.height);
        //清空画布

        //出管
        var datas=[0,0,0,0,0,0,0,0,0,0,0,0];
        var colors=["#303030","#cc9010"];//银灰色(黑)，泥巴黄
        for(var i=0+(currentGroup-1)*12;i<(currentGroup)*12;i++){
            datas[i%12]=tubeOutTempData[i].temp;
//            console.log("debug datas",datas[i],"index",i);
        }
        if(currentPainState===0)
            Painter.paintLinearLines(canvas,datas,colors);
        else
            Painter.paintRectTable(canvas,datas,colors,2);

        //入管
        colors[0]="#303030";
        colors[1]="#45cc45";

        for(var i=0+(currentGroup-1)*12;i<(currentGroup)*12;i++){
            datas[i%12]=tubeInTempData[i].temp;
        }
        if(currentPainState===0)
            Painter.paintLinearLines(canvas,datas,colors);
        else
            Painter.paintRectTable(canvas,datas,colors,1);

        //cot
        colors[0]="#303030";
        colors[1]="#12cccc";

        for(var i=0+(currentGroup-1)*12;i<(currentGroup)*12;i++){
            datas[i%12]=800+Math.random()*20;//??800+随机数
        }
        if(currentPainState===0)
            Painter.paintLinearLines(canvas,datas,colors);
        else
            Painter.paintRectTable(canvas,datas,colors,3);

        //绘制坐标
        if(currentPainState===0){
            Painter.paintCoordinate1(canvas,currentGroup,-26);
        }
        else{
            Painter.paintCoordinate1(canvas,currentGroup,20);
        }

        canvas.requestPaint();
    }



    //处理炉号和管号变化后的触发
    onCurrentGroupChanged: {
        refreshNewestDatas();
    }
    onCurrentStoveChanged: {
        currentGroup=1;
        refreshNewestDatas();
    }

    //初始化数据
    Component.onCompleted: {
        refreshNewestDatas();
    }

    //串口数据缓存触发
    //datas格式

    Timer{
        id:completeTimer
        interval: 1000
        onTriggered: {
            var datas=serialPortManager.revDatas;
            serialPortManager.revDatas="";
            console.log("datas:\n",datas);
            var ok=checkStr(datas);
            //错误提示框
            if(!ok){
                serialPortManager.closeSerialPort();
                readyReciveData=false;

                var component = Qt.createComponent("qrc:/UI/Widgets/ErrorDialog.qml");
                if (component.status === Component.Ready) {//??会阻塞吗如果界面大写状态为Component.Loading
                    var errordialog = component.createObject(root);
                    errordialog.errorStr="  由于接收的数据不完整导致数据导入失败，请重新打开串口接收数据，建议遥控存的数据不要超过三组，以提高数据接收完整度";
                    errordialog.open();
                }
                return;
            }

            var value=datas.toString().split("??");


            /*删除换行符的数据，占两个字符*/
            for(var a=0;a<value.length;a++){
                if(value[a].length===2){
                    value.splice(a,1);
                }
            }

            var count=value.length/9;

            for(var index=0;index<count;index++){
                console.log("header:",value[9*index+0]);
                //??为什么特地+0
                //取每组的日期存到date
                var date=value[9*index+0].substr(value[9*index+0].indexOf("<")+1,8);
                console.log("date:",date);
                /*年*/
                var year=String(date).substring(0,4);
                console.log("year:",year);
                /*月*/
                var month=String(date).substring(4,6);
                console.log("month",month);
                /*日*/
                var day=String(date).substring(6,8);
                console.log("day",day);

                /*转换*/
                date=year+"-"+month+"-"+day;
                console.log("Date",date);

                /*时间*/
                var time=String(value[9*index+0]).split("-")[1];
                console.log("time:",time);
                /*时*/
                var hours=String(time).split(":")[0];
                if(Number(hours)<10)
                    hours="0"+String(Number(hours));
                else
                    hours=String(Number(hours));

                /*分*/
                var minute=String(time).split(":")[1];
                if(Number(minute)<10)
                    minute="0"+String(Number(minute));
                else
                    minute=String(Number(minute));

                /*秒*/
                var second=String(time).split(":")[2];
                if(Number(second)<10)
                    second="0"+String(Number(second));
                else
                    second=String(Number(second));
                /*转换*/
                time=hours+":"+minute+":"+second;


                /*时间+日期*/
                var dateTime=date+" "+time;
                console.log("dateTime convertion:",dateTime);



                /*炉号*/
                var s=Number(String(value[9*index+0]).split("-")[2].charAt(2));
                console.log("炉号",s);


                for(var j=1;j<9;j++){
//                        console.log(j+"号窗口：",value[9*index+j]);
                    var w=Number(String(value[9*index+j]).split("#")[1].charAt(0));
                    console.log("窗口号",w);
                    var temp18s=String(value[9*index+j]).split(",")

                    //g=4;location=tube_in
                    var g=4;
                    var location="tube_in";

                    if(w===1){
                        g=4;
                        location="tube_in";
                    }
                    else if(w===2){
                        g=4;
                        location="tube_out";
                    }
                    else if(w===3){
                        g=3;
                        location="tube_out";
                    }
                    else if(w===4){
                        g=3;
                        location="tube_in";
                    }
                    else if(w===5){
                        g=2;
                        location="tube_in";
                    }
                    else if(w===6){
                        g=2;
                        location="tube_out";
                    }
                    else if(w===7){
                        g=1;
                        location="tube_out";
                    }
                    else if(w===8){
                        g=1;
                        location="tube_in";
                    }

                    //切割的字符串为这个，第一个和最后一个是废的
//                    5#1,896,894,896,890,898,883,898,885,896,897,882,881,10694
//                    temp18s即为以上数组
                    for(var a=1;a<temp18s.length-1;a++){
                        var tubenum=a+(g-1)*12;
                        var temp=Number(temp18s[a]);
//                        console.log("temp:",temp18s[a],"   ",a);
                        server.pushDatas(String(tubenum),String(s),String(location),String(temp),String(dateTime));
                        //管号，炉号，进出管，值，时间
                    }
//                    console.log("group:",g,"tubenum:",tubenum,"foruneNum:",s,"location:",location,"temp:",temp,"datetime:",dateTime);


//                    //数据测试正确
//                    console.log(w+"号窗口",
//                                temp18s[1],
//                                temp18s[2],
//                                temp18s[3],
//                                temp18s[4],
//                                temp18s[5],
//                                temp18s[6],
//                                temp18s[7],
//                                temp18s[8],
//                                temp18s[9],
//                                temp18s[10],
//                                temp18s[11],
//                                temp18s[12]
//                                );

                }
            }


            //关闭串口（必须）
            serialPortManager.closeSerialPort();
            readyReciveData=false;

            //调用反馈器
            serialPortManager.writeDates("Data_Receive_Success!");

            //关闭导入数据对话框
            dataImportDialog.close();

            //显示成功导入数据对话框
            var msgComponent = Qt.createComponent("qrc:/UI/Widgets/MessageDialog.qml");
            if (msgComponent.status === Component.Ready) {
                var msgDialog = msgComponent.createObject(root);
                msgDialog.errorStr="    数据导入成功！";
                msgDialog.open();
            }
            //刷新数据
            refreshNewestDatas();

        }
    }

    //反馈计时器
    Timer{
        id:responseTimer
        interval: 2000
        onTriggered: {
        }
    }

    //串口设置
    SerialPortManager{

        id:serialPortManager
        onReadingFinish: {//串口收到信息触发
            completeTimer.start();
        }
    }


    //背景
    Rectangle{
        anchors.fill: parent
        color:"#bbbbbb"
    }


    //串口名称列表
    ListModel{
        id:portModel
        Component.onCompleted: {
            for(var i=0;i<serialPortManager.getSerialPortsNum();i++){
                var portname=String(serialPortManager.getSerialPortName(i));
                portModel.append({
                                     "portName":portname,
                                     "isSelected":false

                                 });
                setProperty(0,"isSelected",true);//??感觉可以放外面0换成currentPortIndex
            }
            currentPortNameDisplayText.text="当前选择的串口:"+portModel.get(currentPortIndex).portName;

        }
    }

    //炉号列表
    ListModel{
        id:stoveModel
        Component.onCompleted: {
            for(var a=0;a<11;a++){
                append({
                           "btext":String(a+1)+"号炉",
                           "isSelected":false
                       });
            }
            setProperty(currentStove-1,"isSelected",true);
        }
    }

    //管号列表
    ListModel{
        id:groupModel
        Component.onCompleted: {
            for(var a=0;a<4;a++){
                append({
                           "btext":"第"+String(a+1)+"组",
                           "isSelected":false
                       });
            }
            setProperty(currentGroup-1,"isSelected",true);
        }
    }

    Column{
        anchors.fill: parent
//        spacing:
        id:mainlayout
        Rectangle{
            width: mainlayout.width
            height: 40
            id:topPanel
            color:"#404040"

            Flickable{
                anchors.fill: parent
                contentWidth: row1.width
                Row{
                    id:row1
                    Repeater{
                        model: stoveModel
                        delegate: CheckButton{
                            bntText: btext
                            selected: isSelected
                            //??提议：selected:index==currentStove-1
                            onBntClicked: {
                                for(var i=0;i<stoveModel.count;i++){
                                    if(i===index)
                                        continue;
                                    if(stoveModel.get(i).isSelected){
                                        stoveModel.setProperty(i,"isSelected",false);
                                    }
                                }
                                stoveModel.setProperty(index,"isSelected",true);
                                currentStove=index+1;

                                /*switch stove num*/
                            }
                        }
                    }
                }
            }

        }

        Item{
            width: mainlayout.width
            height: mainlayout.height-mainlayout.spacing*2-topPanel.height
            id:dataPanel

            Rectangle{
                anchors.centerIn: parent
                width:parent.width-20
                height:parent.height-20
                clip:true

                //数据显示模式切换按钮
                StateBnt{
                    id:paintStateButton
                    bntText: currentPainState===0?"切换直方图":"切换线性图"
                    onBntClicked: {
                        currentPainState=currentPainState===0?1:0
                        refreshNewestDatas();
                    }
                    anchors.right: parent.right
                    anchors.rightMargin: 30
                    y:30
                }

                //数据导入按钮
                StateBnt{
                    id:dataImportBnt
                    bntText: "导入新数据"
                    onBntClicked: {
                        //更新串口接口数据
                        //??提议感觉这一块可以写成一个函数
                        portModel.clear();
                        for(var i=0;i<serialPortManager.getSerialPortsNum();i++){
                            var portname=String(serialPortManager.getSerialPortName(i));
                            portModel.append({
                                                 "portName":portname,
                                                 "isSelected":false

                                             });
                            portModel.setProperty(currentPortIndex,"isSelected",true);
                        }
                        //??提议感觉这一块可以写成一个函数
                        //打开对话框
                        dataImportDialog.open();
                    }
                    anchors.right: parent.right
                    anchors.rightMargin: 30
                    anchors.top:paintStateButton.bottom
                    anchors.topMargin: 20
                    y:30
                }



                Row{
                    id:groupRow
                    anchors.horizontalCenter: parent.horizontalCenter
                    spacing: 20
                    Repeater{
                        model: groupModel
                        delegate: RoundBnt{
                            bntText: btext
                            selected: isSelected
                            onBntClicked: {
                                for(var i=0;i<groupModel.count;i++){
                                    if(i===index)
                                        continue;
                                    if(groupModel.get(i).isSelected){
                                        groupModel.setProperty(i,"isSelected",false);
                                    }
                                }
                                groupModel.setProperty(index,"isSelected",true);
                                currentGroup=index+1;

                                /*switch stove num*/
                            }
                        }
                    }

                }


                Column{
                    id:hintRow
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.top:groupRow.bottom
                    anchors.topMargin: 15
                    spacing: 10
                    Row{
                        spacing: 15
                        Rectangle{
                            width: 20
                            height: width
                            color:tube_in_content_color
                        }
                        Text{
                            text:"入管温度"
                            font.pointSize: 17
                            color:"#333333"
                        }
                    }

                    Row{
                        spacing: 15
                        Rectangle{
                            width: 20
                            height: width
                            color:tube_out_content_color
                        }
                        Text{
                            text:"出管温度"
                            font.pointSize: 17
                            color:"#333333"
                        }
                    }


                    Row{
                        spacing: 15
                        Rectangle{
                            width: 20
                            height: width
                            color:tube_cot_content_color
                        }
                        Text{
                            text:"COT温度"
                            font.pointSize: 17
                            color:"#333333"
                        }
                    }

                }

                Canvas{
                    id:canvas
                    width: parent.width
                    height: parent.height-40
                    onPaint: {
//                        Painter.paintCoordinate1(canvas,currentGroup);
                    }
                }
            }
        }

    }

    //data import dialog
    Dialog {
        id:dataImportDialog
        title: "无线数据导入"
        contentItem: Rectangle {
            id:itemContent
            color: "#12ccef"
            implicitWidth: 800
            implicitHeight: 450

            Column{
                anchors.fill: parent
                Rectangle{
                    width: itemContent.width
                    height: 40
                    color:"#454545"
                    Flickable{
                        anchors.fill: parent
                        contentWidth: row2.width
                        Row{
                            id:row2
                            Repeater{
                                model: portModel
                                delegate: CheckButton{
                                    bntText: portName
                                    selected: isSelected
                                    onBntClicked: {
                                        currentPortIndex=index;
                                        console.log(portModel.get(index).portName)
                                        for(var i=0;i<portModel.count;i++){
                                            if(i===index)
                                                continue;
                                            if(portModel.get(i).isSelected){
                                                portModel.setProperty(i,"isSelected",false);
                                            }
                                        }
                                        portModel.setProperty(index,"isSelected",true);
                                        currentPortNameDisplayText.text="当前选择的串口:"+portModel.get(currentPortIndex).portName;
                                        //设置串口
                                        serialPortManager.setPortName(portName);
                                    }
                                }
                            }
                        }
                    }
                }
                Item{
                    width: itemContent.width
                    height: itemContent.height-100
                    Text{
                        id:currentPortNameDisplayText
                        anchors.horizontalCenter: parent.horizontalCenter
                        y:20
                        text:"当前选择的串口:"+portModel.get(currentPortIndex).portName
                        color:"#ffffff"
                        font.pointSize: 25
                    }
                    TextArea{
                        width: parent.width-60
                        height: 200
                        anchors.centerIn: parent
                        id:messageText
                        text:readyReciveData?"   正在接收数据中，请用遥控器发送数据到zigbee接收器"
                                            :
                                              "  请选择zigbee接收器串口对应的串口名字，然后再按下打开串口按钮，系统会自动接收遥控器发来的数据，直到接收完毕，如果没有找到串口号，请检擦zigbee接收器是否正常安装驱动。如果不知道哪个串口对应zigbee接收器的，可以先拔出usb线，然后点击导入数据按钮查看串口第一次，然后关闭对话框，重新插入usb线，再点击导入数据按钮查看串口第二次，如果第二次出现了第一次查看串口时没有的串口名，说明这就是对应zigbee接收器的串口！或者在系统中查看串口。"
                        font.pointSize: 20
                        backgroundVisible: false
                        readOnly: true
                        textColor: "#ffffff"
                    }
                }

                Item{
                    width:parent.width
                    height:60
                    Row{
                        anchors.centerIn: parent
                        spacing: 100
                        StateBnt{
                            bntText: readyReciveData?"关闭串口":"打开串口"
                            onBntClicked: {
                                readyReciveData=readyReciveData?false:true
                                if(readyReciveData){
                                    var ok=serialPortManager.openSerialPort();
                                    if(!ok){
                                        //打开串口失败
                                        readyReciveData=false;
                                        serialPortManager.closeSerialPort();
                                        //串口打开错误对话框
                                        var msgComponent = Qt.createComponent("qrc:/UI/Widgets/MessageDialog.qml");
                                        if (msgComponent.status === Component.Ready) {
                                            var msgDialog = msgComponent.createObject(root);
                                            msgDialog.errorStr="    串口打开失败，可能有其他程序在占用此串口，请手动关闭其他占用该串口的程序，再重新打开串口。";
                                            msgDialog.open();
                                        }
                                    }
                                    //感觉缺少接受串口数据的触发吗
                                    //错觉吧，应该是设置端口名后当数据流入会自动触发槽
                                }
                                else{
                                    serialPortManager.closeSerialPort();
                                }
                            }
                        }
                        StateBnt{
                            bntText: "取消"
                            onBntClicked: {
                                if(readyReciveData){
                                    readyReciveData=false;
                                }
                                dataImportDialog.close();
                            }
                        }
                    }
                }
            }


        }
    }

}

